let map, underground, bgl = null, dxk = null, zmlDs = null, xt = null, jxl = null, nightVisionEffect = null,
    rainEffect = null, fogEffect = null, snowEffect = null, snowCover = null;
let nightVisionEnable = false, rainEffectEnable = false, fogEffectEnable = false, snowEffectEnable = false;
const OfflineCache = CesiumNetworkPlug.OfflineCacheController

OfflineCache.ruleList.add("*")

export function mapCreate(idName, back) {
    map = new mars3d.Map(idName, {
        // 配置地球的可见性为false
        scene:
            {
                center:{"lat":39.104221,"lng":115.968697,"alt":53429.8,"heading":360,"pitch":-90},
                requestRenderMode: true, //开启显式渲染
                preloadWhenHidden: true,
                useWebVR: false,
                showSun: true,
                showMoon: true,
                showSkyBox: true,
                showSkyAtmosphere: false, // 关闭球周边的白色轮廓 map.scene.skyAtmosphere = false
                fog: true,
                fxaa: true,
                globe: {
                    showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
                    depthTestAgainstTerrain: false,
                    baseColor: "#546a53"
                },
                cameraController: {
                    zoomFactor: 3.0,
                    minimumZoomDistance: 1,
                    maximumZoomDistance: 50000000,
                    enableRotate: true,
                    enableZoom: true
                }
            },
        control: {
            baseLayerPicker: false, // basemaps底图切换按钮
            homeButton: false, // 视角复位按钮
            sceneModePicker: false, // 二三维切换按钮
            navigationHelpButton: false, // 帮助按钮
            fullscreenButton: false, // 全屏按钮
            contextmenu: { hasDefault: true } // 右键菜单
        },
        terrain: {
            url: "//data.mars3d.cn/terrain",
            show: true
        },
        basemaps: [
            {
                "id": 2017,
                "pid": 10,
                "name": "蓝色底图",
                "icon": "/img/basemaps/bd-c-midnight.png",
                "type": "gaode",
                "layer": "vec",
                "chinaCRS": "GCJ02",
                "invertColor": true,
                "filterColor": "#4e70a6",
                "brightness": 0.6,
                "contrast": 1.8,
                "gamma": 0.3,
                "hue": 1,
                "saturation": 0
            },
            {
                "pid": 10,
                "name": "黑色底图",
                "icon": "/img/basemaps/bd-c-dark.png",
                "type": "gaode",
                "layer": "vec",
                "chinaCRS": "GCJ02",
                "invertColor": true,
                "filterColor": "#909090",
                "brightness": 0.6,
                "contrast": 1.8,
                "gamma": 0.3,
                "hue": 1,
                "saturation": 0
            },
        ],
        shadows: true, // 是否启用日照阴影
        removeDblClick: true, // 是否移除Cesium默认的双击事件
    });
    map.basemap = "2017" // 切换至蓝色底图
    map.terrainProvider = mars3d.LayerUtil.getNoTerrainProvider();
    back(map);
    return map;
}

export function setNightVision() {
    nightVisionEnable = !nightVisionEnable;
    nightVisionEffect.enabled = nightVisionEnable;
}

export function setRainEffect() {
    rainEffectEnable = !rainEffectEnable;
    rainEffect.enabled = rainEffectEnable;
}

export function setFogEffect() {
    fogEffectEnable = !fogEffectEnable;
    fogEffect.enabled = fogEffectEnable;
}

export function setSnowEffect() {
    snowEffectEnable = !snowEffectEnable;
    snowEffect.enabled = snowEffectEnable;
    snowCover.enabled = snowEffectEnable;
}

/**
 * 获取3dTiles模型对象
 * @param name
 * @param url
 * @returns {TilesetLayer}
 */
export function getTilesetLayer(name, url, options = {}) {
    let config = {
        pid: 2020,
        type: "3dtiles",
        name: name,
        url: url,
        maximumScreenSpaceError: 16, // 【重要】数值加大，能让最终成像变模糊
        maximumMemoryUsage: 1024, // 【重要】内存建议显存大小的50%左右，内存分配变小有利于倾斜摄影数据回收，提升性能体验
        // clampToGround: true //贴地显示
    }
    return new mars3d.layer.TilesetLayer(Object.assign(config, options))
}


export function setCameraView(position, back) {
    map.setCameraView(position, {
        complete: () => {
            if (back) {
                back();
            }
        }
    })
}

export function roam() {
    let fixedRoute = new mars3d.graphic.FixedRoute({
        name: "步行路线",
        speed: 200,
        autoStop: true, // 到达终点自动停止
        positions: [
            [87.452652, 43.869038, 10],
            [87.453525, 43.869021, 10],
            [87.454678, 43.869007, 10],
            // [87.454684, 43.868974, 10],
            // [87.454676, 43.868169, 10]
        ],
        camera: {
            type: "dy",
        },
    })
    // this.graphicLayer.addGraphic(fixedRoute)
    fixedRoute.on(mars3d.EventType.endItem, function (event) {
        console.log("已漫游过点：" + event.index, event)
    })
    fixedRoute.on(mars3d.EventType.end, (event) => {
        console.log("漫游结束", event)
        map.setCameraView({
            "lat": 43.872647, "lng": 87.457346, "alt": 113.7, "heading": 155.6, "pitch": -13.1,
            roll: 0.1
        });
    });
    fixedRoute.start()
}

/**
 * vr开关
 * @param map
 */
export function vrOperate(map, value = true) {
    // 这句话打开VR
    map.scene.useWebVR = value

}

export function vrOpen() {
    map.scene.useWebVR = true;
}


/**
 * 设置监控视频
 */
export function setMonitorCamera(graphicLayer, array, isDs = true) {
    array.forEach(item => {
        addRandomGraphicByCount(graphicLayer, item, isDs);
    });

}

/**
 * 添加摄像头监控
 * @param graphicLayer
 * @param position
 */
function addRandomGraphicByCount(graphicLayer, position, isDs = true) {
    const graphicImg = new mars3d.graphic.DivGraphic({
        position: position,
        style: {
            html: ` <div class="mars3d-camera-content">
                      <img class="mars3d-camera-img" src="https://file.xushiyun.cn/oreWisdom/camera.svg" >
                    </div>
                    <div class="mars3d-camera-line" ></div>
                    <div class="mars3d-camera-point"></div>
                  `,
            offsetX: -16,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 100000)
        },
        popup: isDs ? `<video src='http://data.mars3d.cn/file/video/lukou.mp4' controls autoplay style="width: 300px;" ></video>` : `<video src='https://c-road-1304560726.cos.ap-nanjing.myqcloud.com/shipin%2Fjinxiawurenji1.mp4' controls autoplay style="width: 300px;" ></video>`,
        popupOptions: {
            offsetY: -170, // 显示Popup的偏移值，是DivGraphic本身的像素高度值
            template: `<div class="marsBlackPanel animation-spaceInDown">
                        <div class="marsBlackPanel-text">{content}</div>
                        <span class="mars3d-popup-close-button closeButton" >×</span>
                      </div>`,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            verticalOrigin: Cesium.VerticalOrigin.CENTER
        }
    })
    graphicLayer.addGraphic(graphicImg)
}


/**
 * 修改tileset属性  单体化需求
 * @param tilesetLayer
 * @param modelArray
 */
export function modifyModelAttribute(tilesetLayer, modelArray) {
    const idField = "id" // 唯一标识对应的属性字段名称
    const newProperties = {}
    const loadFeatureList = new mars3d.MarsArray()
    tilesetLayer.readyPromise.then(() => {
        bindSetPropertiesToTile(tilesetLayer.tileset)
        modelArray.forEach(item => {
            addProperties(item);
        })
    })


    function bindSetPropertiesToTile(tileset) {
        tileset.tileLoad.addEventListener(function (tile) {
            processTileFeatures(tile, (feature) => {
                const id = feature.getProperty(idField)
                const attr = newProperties[id]
                if (id && attr) {
                    setFeatureProperties(feature, attr)
                    loadFeatureList.set(id, feature)
                }
            })
        })

        tileset.tileUnload.addEventListener(function (tile) {
            processTileFeatures(tile, (feature) => {
                const id = feature.getProperty(idField)
                if (id) {
                    loadFeatureList.remove(id)
                }
            })
        })
    }

// 增加属性
    function addProperties(properties) {
        const id = properties[idField]
        newProperties[id] = properties
    }

// 移除属性
    function removeProperties(properties) {
        const id = properties[idField]
        if (id) {
            delete newProperties[id]

            const feature = loadFeatureList.get(id)
            setFeatureProperties(feature, properties)
        }
    }

    function processTileFeatures(tile, callback) {
        const content = tile.content
        const innerContents = content.innerContents
        if (Cesium.defined(innerContents)) {
            const length = innerContents.length
            for (let i = 0; i < length; ++i) {
                processContentFeatures(innerContents[i], callback)
            }
        } else {
            processContentFeatures(content, callback)
        }
    }

    function processContentFeatures(content, callback) {
        const featuresLength = content.featuresLength
        for (let i = 0; i < featuresLength; ++i) {
            const feature = content.getFeature(i)
            callback(feature)
        }
    }

// 更新feature属性
    function setFeatureProperties(feature, newAttr) {
        if (!feature || !newAttr) {
            return
        }

        for (const key in newAttr) {
            const val = newAttr[key]
            if (feature.hasProperty(key) && feature.getProperty(key) === val) {
                continue
            }
            feature.setProperty(key, val)
        }
    }
}

/**
 * 添加gltf模型
 * @param graphicLayer
 * @param modalDataArray
 */
export function addGltfModelData(graphicLayer, modalDataArray) {
    modalDataArray.forEach(item => {
        const graphic = new mars3d.graphic.ModelPrimitive(item);
        graphicLayer.addGraphic(graphic)
    })

}
